<template>
    <view class="order">
        <view v-if="orderProduct.typeId == 0" class="address">
            <view class="address-main" v-if="orderProduct.receiver" @click="goaddress">
                <view class="address-left">
                    <view>
                        <image src="https://smosun-minapp.oss-cn-shanghai.aliyuncs.com/weapp/img/mall/address.png" mode=""></image>
                    </view>
                    <view class="address-title">
                        <view class="address-name">
                            {{ orderProduct.receiver }}
                            <text>{{ orderProduct.contactNumber }}</text>
                        </view>
                        <view class="address_title">地址：{{ orderProduct.receiverAddress }}</view>
                    </view>
                </view>
                <view class="address-right">
                    <image src="https://smosun-minapp.oss-cn-shanghai.aliyuncs.com/weapp/img/mall/address-right.png" mode=""></image>
                </view>
            </view>
            <view class="address-main" v-else @click="goaddress">
                <view class="address-left">
                    <image src="https://smosun-minapp.oss-cn-shanghai.aliyuncs.com/weapp/img/search/add.png" mode=""></image>
                    添加收货地址
                </view>
                <view class="address-right">
                    <image src="https://smosun-minapp.oss-cn-shanghai.aliyuncs.com/weapp/img/mall/address-right.png" mode=""></image>
                </view>
            </view>
        </view>

        <view class="order-main">
            <view class="order-item">
                <view class="order-icon">
                    <image :src="orderProduct.picAbsolute" style="width: 100%; height: 100%; background-color: #eaeaea">
                    </image>
                </view>
                <view class="order-title">
                    <view class="orderTitle">{{ orderProduct.name || orderProduct.goodsName }}</view>
                    <view class="order-tag">{{ getSkuString() }}</view>
                    <view class="order-price">
                        <view>¥{{ orderProduct.salesPrice || 0 || orderProduct.unitPrice || 0 }}</view>
                        <view>*{{ orderProduct.number }}</view>
                    </view>
                </view>
            </view>
            <view class="order-item1">
                <view>商品金额</view>
                <view>¥{{ orderProduct.goodsPrice || 0.0 }}</view>
            </view>
            <view class="order-item1">
                <view>运费</view>
                <view>包邮</view>
            </view>
            <view class="order-item1">
                <view>等级折扣</view>
                <view>-¥{{ orderProduct.gradeDiscountAmount || 0.0 }}</view>
            </view>

            <view class="order-item1" @click="toChooseCoupon">
                <view>优惠券</view>
                <view
                    :style="{
                        color:
                            orderProduct.memCouponList && orderProduct.memCouponList.length === 0 ? '#999' : '#282828',
                    }"
                >
                    {{
                        !orderProduct.discountAmount &&
                        orderProduct.memCouponList &&
                        orderProduct.memCouponList.length === 0
                            ? '无优惠券可用'
                            : ''
                    }}
                    {{
                        !orderProduct.discountAmount &&
                        orderProduct.memCouponList &&
                        orderProduct.memCouponList.length > 0
                            ? `${orderProduct.memCouponList.length}个优惠券可用`
                            : ''
                    }}
                    {{ orderProduct.discountAmount ? `-¥${orderProduct.discountAmount.toFixed(2)}` : '' }}
                    <image src="https://smosun-minapp.oss-cn-shanghai.aliyuncs.com/weapp/img/mall/address-right.png" mode=""></image>
                </view>
            </view>

            <view
                v-if="pointsExchangeRatio != 0 && orderProduct.useableScore > 0 && loadingShow == false"
                class="order-item1"
                @click="falg = true"
            >
                <view>积分</view>
                <view>
                    {{
                        useScore == 0 || useScore == ''
                            ? '不使用'
                            : '使用' + useScore + '积分抵扣¥' + (useScore / pointsExchangeRatio).toFixed(2)
                    }}
                    <image src="https://smosun-minapp.oss-cn-shanghai.aliyuncs.com/weapp/img/mall/address-right.png" mode=""></image>
                </view>
            </view>

            <view class="order-bottom">
                <view>备注</view>
                <view
                    ><input
                        type="text"
                        v-model="orderProduct.remark"
                        placeholder="输入备注信息"
                        placeholder-style="font-size:26rpx;color:#999"
                /></view>
            </view>
        </view>

        <view class="footer">
            <view class="footer-item1">
                合计：
                <text style="font-size: 24rpx; color: #ff413b">¥</text>
                <text v-if="pointsExchangeRatio != 0" style="font-size: 36rpx; color: #ff413b">
                    {{ (orderProduct.amount - (useScore / pointsExchangeRatio).toFixed(2) || 0).toFixed(2) }}
                </text>
            </view>
            <view @click="payEvent()" class="footer-item2">去支付</view>
        </view>
        <product-sku :show="show" @close="close" @open="open"></product-sku>
        <mall-intergral
            v-if="requestLoading"
            :minScore="orderProduct.minScore"
            @useScoreEvent="useScoreEvent"
            :maxScore="orderProduct.maxScore"
            :userScore="orderProduct.useableScore"
            :pointsExchangeRatio="pointsExchangeRatio"
            :falg="falg"
            @close1="close1"
            @open1="open1"
        ></mall-intergral>
    </view>
</template>
<script>
export default {
    data() {
        return {
            addfalg: true,
            falg: false,
            orderProduct: {},
            address: {},
            pointsExchangeRatio: '1',
            useScore: 0,
            preForm: {},
            loadingShow: true,
            loading: false,
            couponList: [1, 2],
            optionsParams: {},
            requestLoading: true,
        };
    },
    onShow() {
        uni.$once('address', (query) => {
            this.address = query;
            this.orderProduct.addressId = this.address.id;
            this.orderProduct.receiver = this.address.name;
            this.orderProduct.receiverAddress = this.address.address;
            this.orderProduct.contactNumber = this.address.phone;
        });
        uni.$once('addressList', (addressList) => {
            var isHave = false;
            addressList.forEach((item) => {
                if (item.id == this.orderProduct.addressId) {
                    isHave = true;
                }
            });
            if (isHave == false) {
                this.address = {};
                this.orderProduct.addressId = '';
                this.orderProduct.receiver = '';
                this.orderProduct.receiverAddress = '';
                this.orderProduct.contactNumber = '';
            }
        });
        this.requestConfig();
    },
    methods: {
        couponClose() {
            this.couponShow = false;
        },
        goaddress() {
            this.helper.navigateTo('/packageMall/pages/address/addressList?fromOrder=1');
        },

        close1() {
            this.falg = false;
        },
        open1() {},
        useScoreEvent(val) {
            this.useScore = val;
            this.falg = false;
        },
        requestConfig() {
            this.request.httpTokenRequest('/mp-api/wx/config/sysconfig', null, 'POST', false).then((res) => {
                if (res.code == 0) {
                    this.loadingShow = false;
                    this.pointsExchangeRatio = res.data.pointsExchangeRatio;
                    this.orderProduct.maxScore = Math.min(this.orderProduct.maxScore, this.orderProduct.useableScore);
                }
            });
        },
        preOrder() {
            let params = {
                ...this.optionsParams,
            };
            if (this.selectCoupon.couponTemplateNo) {
                params.couponNo = this.selectCoupon.couponNo;
            }
            this.requestLoading = false;
            this.request
                .httpTokenJsonRequest('/mp-api/wx/order/pre', params, 'POST', false)
                .then((res) => {
                    if (res.code == 0) {
                        this.orderProduct = Object.assign({}, this.orderProduct, res.data);
                        var specsKey = '';
                        this.orderProduct.specsDataList.forEach((item) => {
                            item.childs.forEach((subItem) => {
                                if (specsKey == '') {
                                    specsKey = subItem.specsName;
                                } else {
                                    specsKey = specsKey + ',' + subItem.specsName;
                                }
                            });
                        });
                        this.orderProduct.specsKey = specsKey;
                        if (this.address.id) {
                            this.orderProduct.addressId = this.address.id;
                            this.orderProduct.receiver = this.address.name;
                            this.orderProduct.receiverAddress = this.address.address;
                            this.orderProduct.contactNumber = this.address.phone;
                        }
                        this.requestConfig();
                    } else if (code > 0) {
                        setTimeout(() => {
                            uni.navigateBack();
                        }, 1000);
                    }
                    this.requestLoading = true;
                })
                .catch(() => {
                    this.requestLoading = true;
                });
        },
        orderUpdateAddress() {
            var form = {
                addressId: this.address.id,
                id: this.orderProduct.id,
            };
            this.request.httpTokenJsonRequest('/mp-api/wx/order/update/address', form, 'POST', false).then((res) => {
                if (res.code == 0) {
                    this.orderProduct = res.data;
                }
            });
        },
        getSkuString() {
            var skuString = '';
            if (this.orderProduct.specsDataList) {
                this.orderProduct.specsDataList.forEach((item) => {
                    if (skuString == '') {
                        skuString = item.specsName + ':' + (item.childs.length > 0 ? item.childs[0].specsName : '');
                    } else {
                        skuString =
                            skuString +
                            ',' +
                            item.specsName +
                            ':' +
                            (item.childs.length > 0 ? item.childs[0].specsName : '');
                    }
                });
                return skuString;
            }
        },
        payEvent() {
            if (this.loading) {
                return;
            }
            if (this.orderProduct.addressId == 0&&this.orderProduct.typeId===0) {
                uni.showToast({
                    title: '收货地址不能为空',
                    icon: 'none',
                });
                return;
            }
            var form = {
                id: this.orderProduct.id,
                remark: this.orderProduct.remark,
            };
            this.preForm.remark = this.orderProduct.remark;
            this.preForm.useScore = this.useScore;
            this.preForm.addressId = this.orderProduct.addressId;
            this.preForm.couponNo = this.orderProduct.couponNo;
            let that = this;
            that.loading = true;
            uni.requestSubscribeMessage({
                tmplIds: [
                    'xX3kwdzC5I-61OxI_yUIGhO_BozN7a8U-PVGjORIlJU',
                    '4WlKLcNqWHQxN6WYburUGD8GdmGg7IcRmDg0x3u_Rds',
                    'OB01OzknOemOioXmf-SzbogLAC8FjjFhRuxKxLX7uUM',
                ],
                complete(res) {
                    that.request
                        .httpTokenJsonRequest('/mp-api/wx/order/pay', that.preForm, 'POST', false)
                        .then((res) => {
                            if (res.code == 0) {
                                if (res.data.order && res.data.pay) {
                                    var orderId = res.data.order.id;
                                    var payData = res.data.pay;
                                    uni.requestPayment({
                                        provider: 'wxpay',
                                        timeStamp: payData.timeStamp,
                                        nonceStr: payData.nonceStr,
                                        package: payData.packageValue,
                                        signType: payData.signType,
                                        paySign: payData.paySign,
                                        success: (payRes) => {
                                            uni.redirectTo({
                                                url: '/packageMall/pages/payend/payend',
                                            });
                                        },
                                        fail: (err) => {
                                            uni.redirectTo({
                                                url: `/packageOrder/pages/orderlist/orderDetail?id=${orderId}`,
                                            });
                                        },
                                    });
                                } else {
                                    uni.redirectTo({
                                        url: '/packageMall/pages/payend/payend',
                                    });
                                }
                            } else {
                                that.loading = false;
                            }
                        })
                        .catch((err) => {
                            that.loading = false;
                        });
                },
            });
        },
        toChooseCoupon() {
            if (this.orderProduct.memCouponList.length === 0) {
                return;
            }
            this.$store.commit('setSelectCouponList', [
                ...(this.orderProduct.memCouponList || []),
                ...(this.orderProduct.notAvailableCouponList || []),
            ]);
            uni.navigateTo({
                url: '/packageMall/pages/chooseCoupon/index',
            });
        },
    },
    onLoad(option) {
        if (option.orderProduct) {
            this.orderProduct = JSON.parse(decodeURIComponent(option.orderProduct));
            this.preForm = JSON.parse(decodeURIComponent(option.orderProduct));
            this.optionsParams = JSON.parse(decodeURIComponent(option.orderProduct));
            this.preOrder();
        }
    },
    onUnload() {
        this.$store.commit('cleanSelectCouponItem');
        this.address = {};
    },
    computed: {
        selectCoupon() {
            return this.$store.getters['getSelectCouponItem'];
        },
    },
    watch: {
        selectCoupon() {
            this.useScore = 0;
            this.preOrder();
        },
    },
};
</script>

<style scoped lang="scss">
.footer {
    width: 100%;
    padding: 28rpx 30rpx 24rpx;
    background-color: #fff;
    box-sizing: border-box;
    display: flex;
    align-items: center;
    justify-content: space-between;
}

.footer-item1 {
    font-size: 32rpx;
    color: #333;
    line-height: 44rpx;
    font-weight: 500;
}

.footer-item2 {
    width: 220rpx;
    height: 80rpx;
    line-height: 80rpx;
    font-size: 28rpx;
    background: linear-gradient(180deg, #46c09e 0%, #156d4f 100%);
    box-shadow: 0px 24rpx 48rpx 0px rgba(55, 168, 148, 0.2);
    border-radius: 24rpx;
}
</style>
